package gsfordservlet.repository;

import gsfordservlet.domain.BrokerInfo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

/**
 *  
 * @author Kyungbaek Kim <kyungbaekkim@gmail.com>
 * @version 2012.0202 (YYYY.MMDD)
 * @since 1.6 (Java Version)
 */
public class JdbcBrokerInfoDao extends SimpleJdbcDaoSupport {
    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    public List<BrokerInfo> getBrokerInfoList() {
        logger.info("Getting GsfordEvents!");
        List<BrokerInfo> brokers = getSimpleJdbcTemplate().query(
                "select id, bip, bport from broker_info", 
                new BrokerInfoMapper());
        return brokers;
    }

    public void addBrokerInfo(BrokerInfo binfo) {
        logger.info("Saving BrokerInfo: " + binfo.toString());
        int count = getSimpleJdbcTemplate().update(
        	"insert into broker_info (bip, bport) " +
        	"values (:bip, :bport)",
        	new MapSqlParameterSource().addValue("bip", binfo.getBip())
        		.addValue("bport", binfo.getBport())
        	);            
        logger.info("Rows affected: " + count);
    }
    
    private static class BrokerInfoMapper implements ParameterizedRowMapper<BrokerInfo> {
        public BrokerInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            BrokerInfo binfo = new BrokerInfo();
            binfo.setId(rs.getInt("id"));
            binfo.setBip(rs.getString("bip"));
            binfo.setBport(rs.getInt("bport"));      
            return binfo;
        }

    }
}
